#include "pathdialog.h"
#include "ui_pathdialog.h"
#include <QStringBuilder>
#include <cmath>  // 为了使用 std::exp

// 通行时间模型常数 c
const double TIME_COEFFICIENT = 0.02;

PathDialog::PathDialog(QWidget *parent,
                       const std::vector<Edge*>& path,
                       double totalLength,
                       Vertex* startVertex) :
    QDialog(parent),
    ui(new Ui::PathDialog),
    m_path(path),
    m_totalLength(totalLength),
    startVertex(startVertex)
{
    ui->setupUi(this);
    setWindowTitle("路径详情");
    updatePathDisplay();
}

PathDialog::~PathDialog() {
    delete ui;
}

void PathDialog::updatePathDisplay() {
    if (m_path.empty()) {
        ui->pathTextEdit->setPlainText("⚠️ 无可用路径");
        return;
    }

    // 统计总时间
    double totalTime = 0.0;

    for (Edge* edge : m_path) {
        double ratio = (edge->capacity == 0) ? 0.0
            : static_cast<double>(edge->currentCar) / edge->capacity;
        double fx = (ratio <= 1.0) ? 1.0 : (1.0 + std::exp(ratio));
        double timeCost = TIME_COEFFICIENT * edge->length * fx;
        totalTime += timeCost;
    }

    // 统一显示总长度 + 总耗时（在上方标签）
    ui->lengthLabel->setText(
        QString("总长度: %1 米     总预计耗时: %2 分钟")
        .arg(m_totalLength, 0, 'f', 2)
        .arg(totalTime, 0, 'f', 2)
    );

    // 构建路径信息文本
    QStringList lines;

    Vertex* current = startVertex ? startVertex : m_path.front()->start;
    lines << QString("起点: %1").arg(current->id);

    for (Edge* edge : m_path) {
        Vertex* next = (edge->start == current) ? edge->end : edge->start;

        double ratio = (edge->capacity == 0) ? 0.0
                                             : static_cast<double>(edge->currentCar) / edge->capacity;

        // 分段函数 f(x)
        double fx = (ratio <= 1.0) ? 1.0 : (1.0 + std::exp(ratio));
        double timeCost = TIME_COEFFICIENT * edge->length * fx;

        // 是否超载提示
        QString overloadWarning = (edge->currentCar > edge->capacity) ? "⚠️ 超负荷" : "✅ 正常";

        lines << QString("➡ %1 → %2 | 流量: %3/%4 | 负载率: %5% | %6 | 预计耗时: %7 分钟")
                     .arg(current->id)
                     .arg(next->id)
                     .arg(edge->currentCar)
                     .arg(edge->capacity)
                     .arg(QString::number(ratio * 100, 'f', 1))
                     .arg(overloadWarning)
                     .arg(QString::number(timeCost, 'f', 2));

        current = next;
    }

    ui->pathTextEdit->setPlainText(lines.join("\n"));
}

void PathDialog::on_confirmButton_clicked() {
    accept(); // 关闭对话框
}
